﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Data;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using Meraz.Core.Parsers;
using Meraz.Core.Managers;
using System.Diagnostics;
using Meraz.Core.Helpers;
using Ninject;

namespace Meraz.Core.Commands
{
    public interface ICreateDomainsCommand
    {
        INetworkHelper NetworkHelper { get; set; }
        Domain Execute(string url);
        IDictionary<string, Domain> Execute(IEnumerable<string> urls);
    }

    public class CreateDomainsCommand : BaseCommand, ICreateDomainsCommand 
    {
        [Inject]
        public CreateDomainsCommand(IDomainRepository domainRepo, INetworkHelper networkHelper)
        {
            this.DomainRepository = domainRepo ?? new DomainRepository();
            this.NetworkHelper = networkHelper ?? new NetworkHelper();
        }
        public IDomainRepository DomainRepository { get; set; }
        public INetworkHelper NetworkHelper { get; set; }

        public Domain Execute(string url)
        {
            IDictionary<string, Domain> dict = Execute(new string[] { url });
            return dict[url];
        }
        public IDictionary<string, Domain> Execute(IEnumerable<string> urls)
        {
            Dictionary<string, Domain> dict = new Dictionary<string, Domain>();
            Dictionary<string, Domain> allDomains = new Dictionary<string,Domain>();
            foreach (string url in urls)
            {
                IEnumerable<string> domainNames = NetworkHelper.ExtractDomains(url).Reverse();
                Domain parent = null;
                List<Domain> urlDomains = new List<Domain>();
                for (int domainIndex = 0; domainIndex < domainNames.Count(); domainIndex++)
                {
                    string domainName = domainNames.ElementAt(domainIndex);
                    Domain result = null;
                    //First, was that domain already found?
                    if (allDomains.ContainsKey(domainName))
                        result = allDomains[domainName];

                    //if not, see if the Repository already has it
                    if (result == null)
                        result = DomainRepository.Get(domainName);

                    //else, create it and add it to the Repository
                    if (result == null)
                    {
                        result = new Domain();
                        DomainRepository.Add(result);
                        result.Name = domainName;
                        result.Parent = parent;
                    }
                    parent = result;
                    allDomains[domainName] = result;
                    urlDomains.Add(result);
                }
                dict[url] = urlDomains.LastOrDefault();
            }
            Commit();
            return dict;
        }
    }
}
